<?php

/* @var $this yii\web\View */

use yii\helpers\Html;
use yii\helpers\Url;
use yii\grid\GridView;
use app\models\Message;
use yii\data\ActiveDataProvider;
use app\assets\ComposeAsset;
ComposeAsset::register($this);

$activebox=Yii::$app->request->get('activebox');
if(is_null($activebox)){
  $activebox = 3;
}
$inboxcount=count(Message::find()->where([
  'receiver'=>Yii::$app->user->getId(),
  '(status&8)>>3'=>1,
])->all());
$outboxcount=count(Message::find()->where([
  'sender'=>Yii::$app->user->getId(),
  '(status&4)>>2'=>1,
])->all());
$draftcount=count(Message::find()->where([
  'sender'=>Yii::$app->user->getId(),
  '(status&2)>>1'=>1,
])->all());
//回收站中的消息，如果删除后状态为0
$delcount=count(Message::find()->where(
      '((receiver =:userid and ((status&8)>>3)=0) or '.
      '(sender =:userid and ((status&4)>>2)=0) or '.
      '(sender =:userid and ((status&2)>>1)=0)) and '.
      'status<>0'
      ,[
      'userid'=>Yii::$app->user->getId(),
      ])->all());

switch($activebox){
  case 0://回收站
  $dataProvider = new ActiveDataProvider([
      'query' => Message::find()->select(['id','sender','receiver','title','dt'])->where(
            '((receiver =:userid and ((status&8)>>3)=0) or '.
            '(sender =:userid and ((status&4)>>2)=0) or '.
            '(sender =:userid and ((status&2)>>1)=0)) and '.
            'status<>0'
            ,[
            'userid'=>Yii::$app->user->getId(),
            ])->orderBy(['dt'=>SORT_DESC])->with(['receiver0','sender0']),
      'pagination' => [
          'pageSize' => 20,
      ],
  ]);
  break;
  case 1://草稿
  $dataProvider = new ActiveDataProvider([
    'query' => Message::find()->select(['id','sender','receiver','title','dt'])->where(
          'sender =:userid and ((status&2)>>1)=1'
          ,[
          'userid'=>Yii::$app->user->getId(),
          ])->orderBy(['dt'=>SORT_DESC])->with('receiver0'),
    'pagination' => [
        'pageSize' => 20,
    ],
  ]);
  break;
  case 2://发件箱
  $dataProvider = new ActiveDataProvider([
    'query' => Message::find()->select(['id','sender','receiver','title','dt'])->where(
          'sender =:userid and ((status&4)>>2)=1'
          ,[
          'userid'=>Yii::$app->user->getId(),
          ])->orderBy(['dt'=>SORT_DESC])->with('receiver0'),
    'pagination' => [
        'pageSize' => 20,
    ],
  ]);
  break;
  case 3://收件箱
  $dataProvider = new ActiveDataProvider([
    'query' => Message::find()->select(['id','sender','receiver','title','dt','status'])->where(
          'receiver =:userid and ((status&8)>>3)=1'
          ,[
          'userid'=>Yii::$app->user->getId(),
          ])->orderBy(['dt'=>SORT_DESC])->with('sender0'),
    'pagination' => [
        'pageSize' => 20,
    ],
  ]);
  break;
  default:
    $dataProvider = new ActiveDataProvider([
      'query' => Message::find()->select(['id','sender','receiver','title','dt'])->where(
            'receiver =:userid and ((status&8)>>3)=1'
            ,[
            'userid'=>Yii::$app->user->getId(),
            ])->orderBy(['dt'=>SORT_DESC])->with('sender0'),
      'pagination' => [
          'pageSize' => 20,
      ],
    ]);
  break;
}


$this->title = '消息管理';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="page-title">
  <div>
    <h1><i class="fa fa-envelope"></i> 消息管理</h1>
    <ul class="breadcrumb side">
      <li><i class="fa fa-home fa-lg"></i></li>
      <li class="active"><a href="#">消息管理</a></li>
    </ul>
  </div>

  <div><a class="btn btn-info btn-flat" href="#" id="compose"><i class="fa fa-lg fa-edit"></i> 发消息</a></div>

</div>
  <div class="row">
    <div class="col-md-3 col-sm-6 col-xs-12">
      <div class="widget-small primary coloured-icon <?= ($activebox==3)?'active-box':''?>" boxtype='3'><i class="icon fa fa-envelope fa-3x"></i>
        <div class="info">
          <h4>收件箱</h4>
          <p><b><?=$inboxcount?></b></p>
        </div>
      </div>
    </div>
    <div class="col-md-3 col-sm-6 col-xs-12">
      <div class="widget-small info coloured-icon <?=($activebox==2)?'active-box':''?>" boxtype='2'><i class="icon fa fa-envelope-o fa-3x"></i>
        <div class="info">
          <h4>发件箱</h4>
          <p><b><?=$outboxcount?></b></p>
        </div>
      </div>
    </div>
    <div class="col-md-3 col-sm-6 col-xs-12">
      <div class="widget-small warning coloured-icon <?=($activebox==1)?'active-box':''?>" boxtype='1'><i class="icon fa fa-file-text-o fa-3x"></i>
        <div class="info">
          <h4>草稿</h4>
          <p><b><?=$draftcount?></b></p>
        </div>
      </div>
    </div>
    <div class="col-md-3 col-sm-6 col-xs-12">
      <div class="widget-small danger coloured-icon <?=($activebox==0)?'active-box':''?>" boxtype='0'><i class="icon fa fa-trash-o fa-3x"></i>
        <div class="info">
          <h4>回收站</h4>
          <p><b><?=$delcount?></b></p>
        </div>
      </div>
    </div>
  </div>

<div class='card'>
  <div class="btn-group pull-right">
    <a class="btn btn-info btn-sm del-msg"><i class="fa fa-trash-o"></i></a>
    <a class="btn btn-info btn-sm" href='<?=Url::toRoute(['site/messages','activebox'=>$activebox])?>'><i class="fa fa-refresh"></i></a>
  </div>
  <?php

  //如何提前加载资源
  switch($activebox){
    case 0:
    echo GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
    ['class' => 'yii\grid\CheckboxColumn'],
    // 数据提供者中所含数据所定义的简单的列
    // 使用的是模型的列的数据
    [
      'header'=>'发信人',
      'content'=>function ($model, $key, $index, $column) {
          return $model->sender0->name;
      },
      ],
    [
      'header'=>'收信人',
      'content'=>function ($model, $key, $index, $column) {
          return $model->receiver0->name;
      },
      ],
      [
        'header'=>'标题',
        'content'=>function ($model, $key, $index, $column) {
            return '<a class="content-link" style="cursor:pointer" msgid="'.$model->id.'" readed="1">'.$model->title.'</a>';
        },
        ],
    'dt',
    ],
    'tableOptions' => [
      'class' => 'table table-striped'
    ],
    ]);
    break;
    case 1:
    echo GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
    ['class' => 'yii\grid\CheckboxColumn'],
    // 数据提供者中所含数据所定义的简单的列
    // 使用的是模型的列的数据
    [
      'header'=>'收信人',
      'content'=>function ($model, $key, $index, $column) {
          return $model->receiver0->name;
      },
      ],
      [
        'header'=>'标题',
        'content'=>function ($model, $key, $index, $column) {
            return '<a class="content-link" style="cursor:pointer" msgid="'.$model->id.'" readed="1">'.$model->title.'</a>';
        },
        ],
    'dt',
    ],
    'tableOptions' => [
      'class' => 'table table-striped'
    ],
    ]);
    break;
    case 2:
    echo GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
    ['class' => 'yii\grid\CheckboxColumn'],
    // 数据提供者中所含数据所定义的简单的列
    // 使用的是模型的列的数据
    [
      'header'=>'收信人',
      'content'=>function ($model, $key, $index, $column) {
          return $model->receiver0->name;
      },
      ],
      [
        'header'=>'标题',
        'content'=>function ($model, $key, $index, $column) {
            return '<a class="content-link" style="cursor:pointer" msgid="'.$model->id.'" readed="1">'.$model->title.'</a>';
        },
        ],
    'dt',
    ],
    'tableOptions' => [
      'class' => 'table table-striped'
    ],
    ]);
    break;
    case 3:
    echo GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
    ['class' => 'yii\grid\CheckboxColumn'],
    // 数据提供者中所含数据所定义的简单的列
    // 使用的是模型的列的数据
    [
      'header'=>'发信人',
      'content'=>function ($model, $key, $index, $column) {
          return $model->sender0->name;
      },
      ],
      [
        'header'=>'标题',
        'content'=>function ($model, $key, $index, $column) {
          if((($model->status&16)>>4)==1){
            return '<a class="content-link" style="cursor:pointer" msgid="'.$model->id.'" readed="1">'.$model->title.'</a>';
          }else{
            return '<a class="content-link" style="cursor:pointer" msgid="'.$model->id.'" readed="0"><b>'.$model->title.'</b></a>';
          }
        },
        ],
    'dt',
    ],
    'tableOptions' => [
      'class' => 'table table-striped'
    ],
    ]);
    break;
    default:
    echo GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
    ['class' => 'yii\grid\CheckboxColumn'],
    // 数据提供者中所含数据所定义的简单的列
    // 使用的是模型的列的数据
    [
      'header'=>'发信人',
      'content'=>function ($model, $key, $index, $column) {
          return $model->sender0->name;
      },
      ],
      [
        'header'=>'标题',
        'content'=>function ($model, $key, $index, $column) {
            return '<a class="content-link" style="cursor:pointer" msgid="'.$model->id.'">'.$model->title.'</a>';
        },
        ],
    'dt',
    ],
    'tableOptions' => [
      'class' => 'table table-striped'
    ],
    ]);
    break;
  }

  ?>
</div>

<!-- content -->
<div class="modal fade" id="contentModal" tabindex="-1" role="dialog" aria-labelledby="contentModalLabel" msgid=''>
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header btn-warning">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="contentModalLabel"><i class="fa fa-envelope"></i> 消息详情</h4>
      </div>
      <div class="modal-body">

      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
        <button type="button" class="btn btn-warning" id='message-reply'>回复&gt;&gt;</button>
      </div>
    </div>
  </div>
</div>
<!-- end content -->

<!-- compose -->
<div class="compose">
  <div class="compose-header btn-warning">
    发消息
    <button type="button" class="close compose-close">
      <span>×</span>
    </button>
  </div>

  <div class="compose-body">
    <div id="alerts"></div>
    <div class="btn-toolbar editor" data-role="editor-toolbar" data-target="#editor">
      <div class="btn-group">
        <a class="btn dropdown-toggle" data-toggle="dropdown" title="字体尺寸"><i class="fa fa-text-height"></i>&nbsp;<b class="caret"></b></a>
        <ul class="dropdown-menu">
          <li>
            <a data-edit="fontSize 5">
              <span style="font-size:17px">大</span>
            </a>
          </li>
          <li>
            <a data-edit="fontSize 3">
              <span style="font-size:14px">中</span>
            </a>
          </li>
          <li>
            <a data-edit="fontSize 1">
              <span style="font-size:11px">小</span>
            </a>
          </li>
        </ul>
      </div>

      <div class="btn-group">
        <a class="btn" data-edit="bold" title="加粗 (Ctrl/Cmd+B)"><i class="fa fa-bold"></i></a>
        <a class="btn" data-edit="italic" title="斜体 (Ctrl/Cmd+I)"><i class="fa fa-italic"></i></a>
        <a class="btn" data-edit="strikethrough" title="删除线"><i class="fa fa-strikethrough"></i></a>
        <a class="btn" data-edit="underline" title="下划线 (Ctrl/Cmd+U)"><i class="fa fa-underline"></i></a>
      </div>

      <div class="btn-group">
        <a class="btn" data-edit="insertunorderedlist" title="项目符号"><i class="fa fa-list-ul"></i></a>
        <a class="btn" data-edit="insertorderedlist" title="编号"><i class="fa fa-list-ol"></i></a>
        <a class="btn" data-edit="outdent" title="减少缩进 (Shift+Tab)"><i class="fa fa-dedent"></i></a>
        <a class="btn" data-edit="indent" title="缩进 (Tab)"><i class="fa fa-indent"></i></a>
      </div>

      <div class="btn-group">
        <a class="btn" data-edit="justifyleft" title="左对齐 (Ctrl/Cmd+L)"><i class="fa fa-align-left"></i></a>
        <a class="btn" data-edit="justifycenter" title="居中 (Ctrl/Cmd+E)"><i class="fa fa-align-center"></i></a>
        <a class="btn" data-edit="justifyright" title="右对齐 (Ctrl/Cmd+R)"><i class="fa fa-align-right"></i></a>
        <a class="btn" data-edit="justifyfull" title="两端对齐 (Ctrl/Cmd+J)"><i class="fa fa-align-justify"></i></a>
      </div>

      <div class="btn-group">
        <a class="btn dropdown-toggle" data-toggle="dropdown" title="超链接"><i class="fa fa-link"></i></a>
        <div class="dropdown-menu input-append">
          <input class="span2" placeholder="URL" type="text" data-edit="createLink" />
          <button class="btn" type="button">添加</button>
        </div>
        <a class="btn" data-edit="unlink" title="移除超链接"><i class="fa fa-cut"></i></a>
      </div>
      <div class="btn-group">
        <a class="btn" data-edit="undo" title="拆销 (Ctrl/Cmd+Z)"><i class="fa fa-undo"></i></a>
        <a class="btn" data-edit="redo" title="重做 (Ctrl/Cmd+Y)"><i class="fa fa-repeat"></i></a>
      </div>
    </div>

    <div id="editor" class="editor-wrapper"></div>
  </div>

  <div class="compose-footer">
    <div class='form-inline'>

      <div class='col-md-6 form-group'>
        <div class='input-group'>
            <span class="input-group-addon" id="receiver-label" >收信人</span>
            <?= Html::textInput('message-receiver','',[
              'id'=>'message-receiver',
              'class'=>'form-control',
              'placeholder'=>'请指定收信人的会员名',
              'aria-describedby'=>"receiver-label"
              ])?>
            <span class="input-group-btn">
              <button class="btn btn-warning" type="button" style='padding:8px 12px 7px 12px;' id='send'>发送</button>
            </span>
        </div>
      </div>
      <div class='col-md-6 form-group'>
        <button id="save" class="btn btn-sm btn-info" type="button"  style='padding:8px 12px 7px 12px;width:100%;'>保存为草稿</button>
      </div>
    </div>
    <div class='clearfix'></div>
  </div>
</div>

<!-- /compose -->
<?php $this->beginBlock('compose-js') ?>
/* WYSIWYG EDITOR */

function init_wysiwyg() {

if( typeof ($.fn.wysiwyg) === 'undefined'){ return; }
console.log('init_wysiwyg');

   function init_ToolbarBootstrapBindings() {
     var fonts = ['Serif', 'Sans', 'Arial', 'Arial Black', 'Courier',
         'Courier New', 'Comic Sans MS', 'Helvetica', 'Impact', 'Lucida Grande', 'Lucida Sans', 'Tahoma', 'Times',
         'Times New Roman', 'Verdana'
       ],
       fontTarget = $('[title=Font]').siblings('.dropdown-menu');
     $.each(fonts, function(idx, fontName) {
       fontTarget.append($('<li><a data-edit="fontName ' + fontName + '" style="font-family:\'' + fontName + '\'">' + fontName + '</a></li>'));
     });
     $('a[title]').tooltip({
       container: 'body'
     });
     $('.dropdown-menu input').click(function() {
         return false;
       })
       .change(function() {
         $(this).parent('.dropdown-menu').siblings('.dropdown-toggle').dropdown('toggle');
       })
       .keydown('esc', function() {
         this.value = '';
         $(this).change();
       });

     $('[data-role=magic-overlay]').each(function() {
       var overlay = $(this),
         target = $(overlay.data('target'));
       overlay.css('opacity', 0).css('position', 'absolute').offset(target.offset()).width(target.outerWidth()).height(target.outerHeight());
     });

     if ("onwebkitspeechchange" in document.createElement("input")) {
       var editorOffset = $('#editor').offset();

       $('.voiceBtn').css('position', 'absolute').offset({
         top: editorOffset.top,
         left: editorOffset.left + $('#editor').innerWidth() - 35
       });
     } else {
       $('.voiceBtn').hide();
     }
   }

   function showErrorAlert(reason, detail) {
     var msg = '';
     if (reason === 'unsupported-file-type') {
       msg = "Unsupported format " + detail;
     } else {
       console.log("error uploading file", reason, detail);
     }
     $('<div class="alert"> <button type="button" class="close" data-dismiss="alert">&times;</button>' +
       '<strong>File upload error</strong> ' + msg + ' </div>').prependTo('#alerts');
   }

  $('.editor-wrapper').each(function(){
 var id = $(this).attr('id');	//editor-one

 $(this).wysiwyg({
   toolbarSelector: '[data-target="#' + id + '"]',
   fileUploadError: showErrorAlert
 });
});


   window.prettyPrint;
   prettyPrint();

};


/* COMPOSE */

function init_compose() {
  if( typeof ($.fn.slideToggle) === 'undefined'){ return; }
  console.log('init_compose');

  $('#compose, .compose-close').click(function(){
    $('.compose').slideToggle();
  });

};
$(document).ready(function() {
  init_wysiwyg();
  init_compose();
  //发送消息
  $('#send').click(function(){
    $.ajax({
      url:"<?=Url::toRoute('site/sendmessage')?>",
      type:"get",
      datatype:"json",
      cache:false,
      data:{
        receiver:$('#message-receiver').val(),
        content:$('#editor').html()
      },
      success:function(data){
         var obj = JSON.parse(data);
         alert(obj.errmsg);
         if(obj.errcode===0){
            $('.compose').slideToggle();
         }
      },
      error:function(jqXHR,textStatus,errorThrown){
        console.log(jqXHR);
        console.log(textStatus);
        console.log(errorThrown);
        $('.compose').slideToggle();
      }
    });
  });

  //切换消息箱
  $('.widget-small').click(function(){
    if($(this).hasClass('active-box')){
        return;
    }
    var redirecturl='<?=Url::toRoute('site/messages')?>'+'?activebox='+$(this).attr("boxtype");
    window.open(redirecturl,'_self');
  });

  //显示消息内容
  $('.content-link').click(function(){
    var $this=$(this);
    var mymsgid=$(this).attr('msgid');
    var readed=$(this).attr('readed');
    var myissetreaded=(readed==1)?0:1;
    $.ajax({
      url:"<?=Url::toRoute('site/getmsgcontent')?>",
      type:"get",
      datatype:"json",
      cache:false,
      data:{
        msgid:mymsgid,
        issetreaded:myissetreaded
      },
      success:function(data){
         var obj = JSON.parse(data);
         if(obj.errcode===0){
           //显示消息为已读
           var $title=$this.find('b');
           if(($title!=='undefined')&&($title.length==1)){
              $this.text($title.text());
           }

            $('.compose').hide();
            $('.modal-body').html(obj.errmsg);
            $('#contentModal').attr('msgid',mymsgid);
            //如果是收信内容，显示回复按钮
            if($('.active-box').attr('boxtype')==3){
              $('#message-reply').show();
            }else{
                $('#message-reply').hide();
            }
            $('#contentModal').modal();
         }
      },
      error:function(jqXHR,textStatus,errorThrown){
        console.log(jqXHR);
        console.log(textStatus);
        console.log(errorThrown);
        $('.compose').slideToggle();
      }
    });
  });

  //回复消息
  $('#message-reply').click(function(){
    var mymsgid=$('#contentModal').attr('msgid');
    $.ajax({
      url:"<?=Url::toRoute('site/getmsgsender')?>",
      type:"get",
      datatype:"json",
      cache:false,
      data:{
        msgid:mymsgid
      },
      success:function(data){
         var obj = JSON.parse(data);
         if(obj.errcode===0){
           $('#contentModal').modal('hide');
           $('.compose').slideToggle();
           $('#message-receiver').val(obj.errmsg);
         }
      },
      error:function(jqXHR,textStatus,errorThrown){
        console.log(jqXHR);
        console.log(textStatus);
        console.log(errorThrown);
      }
    });

  });

  //删除消息
  $('.del-msg').click(function(){
    var mykeys = $('.grid-view').yiiGridView('getSelectedRows');
    var myactivebox=$('.active-box').attr('boxtype');
    $.ajax({
      url:"<?=Url::toRoute('site/delmsg')?>",
      type:"get",
      datatype:"json",
      cache:false,
      data:{
        keys:mykeys,
        activebox:myactivebox
      },
      success:function(data){
         var obj = JSON.parse(data);
         if(obj.errcode===0){
            //删除行
            var i=0;
            for (i = 0; i < mykeys.length; i++ )
            {
              $("tr[data-key='"+mykeys[i]+"']").remove();
            }
            //设置新的容器消息数量
            var $boxcount= $('.active-box').find('b');
            $boxcount.text($boxcount.text()-mykeys.length);
         }
      },
      error:function(jqXHR,textStatus,errorThrown){
        console.log(jqXHR);
        console.log(textStatus);
        console.log(errorThrown);
      }
    });

  });

});

<?php $this->endBlock() ?>
<?php $this->registerJs($this->blocks['compose-js'],\yii\web\View::POS_END); ?>
